package com.weharvest.edu.controller;

import com.weharvest.edu.annotation.MenuAnnotion;
import com.weharvest.edu.annotation.PermissionAnnotion;
import com.weharvest.edu.annotation.SignSecurity;
import com.weharvest.edu.config.ProjectConfig;
import com.weharvest.edu.constant.MenuConstant;
import com.weharvest.edu.constant.PermissionConstants;
import com.weharvest.edu.dto.BackstageUserDTO;
import com.weharvest.edu.entity.BackstageUser;
import com.weharvest.edu.enums.ResultEnum;
import com.weharvest.edu.enums.WechatExceptionEnum;
import com.weharvest.edu.exception.WechatException;
import com.weharvest.edu.service.BackstageUserService;
import com.weharvest.edu.utlis.ResultUtil;
import com.weharvest.edu.view.BackstageUserView;
import com.weharvest.edu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin/backstage/user")
@SignSecurity
@MenuAnnotion(value = MenuConstant.BACKSTAGE_USER)
@Slf4j
public class BackstageUserController {

    @Resource
    private BackstageUserService backstageUserService;

    @Resource
    private WxMpService wxOpenService;

    @Resource
    private ProjectConfig projectConfig;

    /**
     * 查看所有后台用户
     *
     * @param backstageUserDTO
     * @param response
     * @param request
     * @return
     */
    @PostMapping("/find")
    @ResponseBody
    @PermissionAnnotion(PermissionConstants.DATA_FIND)
//    @Cacheable(cacheNames = "app",key = "#backstageUserDTO.id")
    public ResultVo<BackstageUserView> find(
            @RequestBody BackstageUserDTO backstageUserDTO,
            HttpServletResponse response,
            HttpServletRequest request) {
        return ResultUtil.success(backstageUserService.find(
                backstageUserDTO, request, response));
    }

    /**
     * 修改
     *
     * @param dto
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/modify")
    @ResponseBody
    public ResultVo modify(
            @RequestBody BackstageUserDTO dto,
            HttpServletRequest request,
            HttpServletResponse response) {
        backstageUserService.modify(dto, request, response);
        return ResultUtil.success(ResultEnum.SUCCESS_MODIFY);
    }


    //删除后台用户
    @PostMapping("/delete")
//    @CacheEvict(cacheNames = "app",key = "10")
    @ResponseBody
    @PermissionAnnotion(PermissionConstants.DATA_REMOVE)
    public ResultVo detele(
            @RequestBody BackstageUserDTO backstageUserDTO,
            HttpServletResponse response,
            HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        backstageUserService.detele(backstageUserDTO, request, response);
        return ResultUtil.success(ResultEnum.SUCCESS_DELETE);
    }

    /**
     * 添加
     *
     * @param dto
     * @param response
     * @param request
     * @return
     */
    @PermissionAnnotion(PermissionConstants.DATA_ADD)
    @PostMapping("/add")
    @ResponseBody
//    @CacheEvict(cacheNames = "app",key = "10")
    public ResultVo add(@RequestBody BackstageUserDTO dto,
                        HttpServletResponse response,
                        HttpServletRequest request) {
        backstageUserService.add(dto, request, response);
        return ResultUtil.success(ResultEnum.SUCCESS_ADD);
    }


    /*********************************************************************/


    //绑定登录者
    @GetMapping("/binding")
    public String binding(@RequestParam(value = "resultUrl",
            defaultValue = "http://sanly.mynatapp.cc/weharvest/edu/index") String resultUrl) {
        //重定向微信认证
        String url = projectConfig.getOpenAuthorizeUrl() + "/weharvest/admin/app/user/qrUserInfo";
        String redirectUrl = "";
        try {
            redirectUrl = wxOpenService.buildQrConnectUrl(url,
                    WxConsts.QrConnectScope.SNSAPI_LOGIN, URLEncoder.encode(resultUrl, "UTF-8"));
        } catch (Exception e) {
            log.error("[微信绑定],{}", e);
            throw new WechatException(WechatExceptionEnum.OPEN_ENCODE_ERROR);
        }
        return "redirect:" + redirectUrl;
    }

    //扫描后返回用户信息
    @GetMapping("/qrUserInfo")
    public ModelAndView qrUserInfo(@RequestParam("code") String code, @RequestParam("state") String resultUrl) {
        //根据code获取accesstoken
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (Exception e) {
            log.error("[微信绑定],{}", e);
            throw new WechatException(WechatExceptionEnum.OPEN_ACCESSTOKEN_ERROR);
        }
        String openid = wxMpOAuth2AccessToken.getOpenId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[微信绑定]用户openid:{" + openid + "},时间:{" + sdf.format(new Date()) + "}");
        //查询是否绑定过管理员
        BackstageUserDTO backstageUserDTO = new BackstageUserDTO();
        backstageUserDTO.setOpenid(openid);
        BackstageUser backstageUser = backstageUserService.findByBackstageOpenid(backstageUserDTO);
        if (null != backstageUser) {
            //返回错误页面
            Map<String, Object> map = new HashMap<>();
            map.put("msg", "对不起！你已经绑定过其他的管理员");
            map.put("url", projectConfig.getOpenAuthorizeUrl() + "/weharvest/edu/index");
            return new ModelAndView("common/error", map);
        }
        return new ModelAndView("redirect:" + resultUrl + "?openid=" + openid);
    }

}
